﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbSharp.Framework.DbObject;
using System.Xml.Linq;
using DbSharp.Framework.Common;

namespace DbSharp.Framework.CaseFile.Parser
{
     
    class SetupStatementParser
    {
        public SetupStatementParser(string caseName, IEnumerable<IStatementDeclaration> listStatement, XElement statementElement)
        {
            Extract(caseName, listStatement, statementElement);
        }


        private void Extract(string caseName, IEnumerable<IStatementDeclaration> listStatement, XElement statementElement)
        {
            var aliasAttribute = statementElement.Attribute("statementAlias");
            string statementAlias = aliasAttribute.Value.Trim();
            IStatementDeclaration statementDeclaration = listStatement.FirstOrDefault(
                sql => StatementDeclarationExt.FindByAlias(sql, statementAlias));

            if (statementDeclaration == null)
            {
                string messageFmt = "statementAlias'{0}' used in Test Case '{1}' cannot be found in sqlDeclarations and procDeclarations";
                string message = string.Format(messageFmt, statementAlias, caseName);
                throw new DbSharpException(message);
            }

            //extract inputArguments for this ProcedureDeclaration
            XElement procInputArgsElement;
            procInputArgsElement = statementElement.Element("inputArguments");
            var inputArgsProcessor = new StatementInputArgsProcessor(procInputArgsElement, statementDeclaration);
            Statement = inputArgsProcessor.StatementWithInArgValues;
        }


        public IStatementDeclaration Statement { get; private set; }
    }
}
